# -*- coding: utf-8 -*-

'''
能力评估模板
'''
from ...pao_python.pao.data import process_db, string_to_date
from ...service.common import find_data, get_info, operation_result, get_string_time
from ...service.buss_pub.bill_manage import BillManageService, OperationType, Status, TypeId
from ...service.mongo_bill_service import MongoBillFilter
from server.pao_python.pao.service.data.mongo_db import MongoService, MongoFilter, C, N, F, as_date


class CompetenceAssessmentService(MongoService):
    def __init__(self, db_addr, db_port, db_name, db_user, db_pwd, inital_password, session):
        self.db_addr = db_addr
        self.db_port = db_port
        self.db_name = db_name
        self.db_user = db_user
        self.db_pwd = db_pwd
        self.inital_password = inital_password
        self.session = session
        self.bill_manage_service = BillManageService(
            db_addr, db_port, db_name, db_user, db_pwd, inital_password, session)

    def get_competence_assessment_list(self, org_list, condition, page, count):
        '''
            获取能力评估列表
            Arguments:
                condition   {dict}      条件
                page        {number}    页码
                count       {number}    条数
        '''
        if 'date_range' in list(condition.keys()):
            condition['start_date'] = condition['date_range'][0]
            condition['end_date'] = condition['date_range'][1]
        keys = ['id', 'elder', 'template_name',
                'start_date', 'end_date', 'user_name']
        values = self.get_value(condition, keys)
        _filter = MongoBillFilter()
        _filter.lookup_bill('PT_User', 'elder', 'id', 'user')\
               .add_fields({'user_name': '$user.name'})\
               .lookup_bill('PT_Assessment_Template', 'template', 'id', 'template')\
               .add_fields({'template_name': '$template.template_name', 'template_type': '$template.template_type'})
        if condition.get('is_nursing'):
            _filter.match(C('template.template_type') == '护理评估')

        _filter.match_bill((C('nursing_time') >= as_date(values['start_date']))
                           & (C('nursing_time') <= as_date(values['end_date']))
                           & (C('id') == values['id'])
                           & (C('elder') == values['elder'])
                           & (C('template_name') == values['template_name'])
                           & (C('user_name').like(values['user_name']))
                           & (C('organization_id').inner(org_list)))\
            .sort({'modify_date': -1})\
            .project({'_id': 0, 'user._id': 0, 'template._id': 0})
        print(_filter.filter_objects)
        res = self.page_query(
            _filter, 'PT_Behavioral_Competence_Assessment_Record', page, count)
        return res

    def update_competence_assessment(self, competence_assessment):
        '''新增/修改能力评估

        Arguments:
            competence_assessment   {dict}      条件
        '''
        res = 'fail'
        # 转换日期格式
        if 'nursing_time' in competence_assessment.keys():
            competence_assessment['nursing_time'] = string_to_date(
                competence_assessment['nursing_time'])
        flag = OperationType.update.value if 'id' in list(
            competence_assessment.keys()) else OperationType.add.value
        competence_assessment = get_info(
            competence_assessment, self.session)
        bill_id = self.bill_manage_service.add_bill(
            flag, TypeId.competenceAssessment.value, competence_assessment, 'PT_Behavioral_Competence_Assessment_Record')
        res = operation_result(bill_id)
        return res

    def delete_competence_assessment(self, competence_assessment_id_list):
        '''删除能力评估

        Arguments:
           competence_assessment_id_list   {ids}      数据id
        '''
        res = 'fail'

        def process_func(db):
            nonlocal res
            ids = []
            if isinstance(competence_assessment_id_list, str):
                ids.append(competence_assessment_id_list)
            else:
                ids = competence_assessment_id_list
            for competence_assessment_id in ids:
                # 查询被删除的数据信息
                data = find_data(db, 'PT_Behavioral_Competence_Assessment_Record', {
                    'id': competence_assessment_id, 'bill_status': 'valid'})
                if len(data) > 0:
                    self.bill_manage_service.add_bill(OperationType.delete.value,
                                                      TypeId.competenceAssessment.value, data[0], 'PT_Behavioral_Competence_Assessment_Record')
            res = 'Success'
        process_db(self.db_addr, self.db_port, self.db_name,
                   process_func, self.db_user, self.db_pwd)
        return res
